/*
 * Copyright (c) 2021 Huawei Device Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.example.wryproject.utils;

import ohos.eventhandler.EventHandler;
import ohos.eventhandler.InnerEvent;
import ohos.utils.zson.ZSONObject;

import com.example.wryproject.bean.LrcContent;
import com.example.wryproject.bean.LyricListBean;
import com.example.wryproject.service.MusicServiceAbility;

import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

/**
 * 获取歌词并解析
 *
 * @since 2021-08-03
 */
public class LyricAnalysisUtil {
    public static final String NO_LYRIC_DATA = "暂未获取到歌词信息";
    public static final String LYRICS_FAN_PATH = "http://gecimi.com/api/lyric/";
    private static List<LrcContent> lrcList;

    public LyricAnalysisUtil() {
    }

    /**
     * 获取音乐歌词
     *
     * @param songName 歌曲名
     * @param singer 歌手名
     */
    public static void getMusicLyric(String songName, String singer) {
        ThreadUtil.runWork(() -> {
            String lyricsFanPath = LYRICS_FAN_PATH + songName + "/" + singer;
            String lyricPath = getLyricPath(lyricsFanPath);
            String lyricData = getLyricData(lyricPath);
            EventHandler eventHandler = MusicServiceAbility.getEventHandler();
            InnerEvent event = InnerEvent.get();
            if (lyricData.equals(NO_LYRIC_DATA)) {
                event.object = NO_LYRIC_DATA;
            } else {
                event.object = getLrcContent();
            }
            eventHandler.sendEvent(event);
        });
    }

    /**
     * 获取歌词地址
     *
     * @param path 歌词饭网站地址
     * @return 歌词地址
     */
    private static String getLyricPath(String path) {
        InputStream data;
        HttpURLConnection conn = null;
        String lyricsFanData;
        LyricListBean lyricBean = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setReadTimeout(2000);
            conn.connect();
            data = conn.getInputStream();
            lyricsFanData = readInputStream(data);
            lyricBean = ZSONObject.stringToClass(lyricsFanData, LyricListBean.class);
        } catch (Exception ignored) {
        } finally {
            assert conn != null;
            conn.disconnect();
        }
        if (lyricBean != null && lyricBean.getCount() != 0) {
            return lyricBean.getResult().get(0).getLrc();
        }
        return NO_LYRIC_DATA;
    }

    /**
     * 获取歌词数据
     *
     * @param path 歌词地址
     * @return 歌词数据
     */
    private static String getLyricData(String path) {
        if (path.equals(NO_LYRIC_DATA)) {
            return NO_LYRIC_DATA;
        }
        InputStream data;
        HttpURLConnection conn = null;
        String lyricData = null;
        try {
            URL url = new URL(path);
            conn = (HttpURLConnection) url.openConnection();
            conn.setDoInput(true);
            conn.setRequestMethod("GET");
            conn.setReadTimeout(2000);
            conn.connect();
            data = conn.getInputStream();
            lyricData = read(data);
        } catch (Exception ignored) {
        } finally {
            conn.disconnect();
        }
        if (lyricData != null) {
            return lyricData;
        }
        return NO_LYRIC_DATA;
    }

    /**
     * 解析输入流
     *
     * @param inputStream 输入流
     * @return 字符串结果
     */
    public static String readInputStream(InputStream inputStream) {
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        byte[] buffer = new byte[1024];
        int length = -1;
        try {
            while ((length = inputStream.read(buffer)) != -1) {
                baos.write(buffer, 0, length);
            }
            baos.flush();
        } catch (IOException e) {
            e.printStackTrace();
        }
        String data = baos.toString();
        try {
            inputStream.close();
            baos.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return data;
    }

    /**
     * 解析歌词
     *
     * @param inputStream 歌词数据流
     * @return 解析结果
     */
    public static String read(InputStream inputStream) {
        lrcList = new ArrayList<>();
        LrcContent mLrcContent = new LrcContent();
        StringBuilder stringBuilder = new StringBuilder();
        try {
            InputStreamReader isr = new InputStreamReader(inputStream);
            BufferedReader br = new BufferedReader(isr);
            String s;
            while ((s = br.readLine()) != null) {
                s += "";
                // 将没有内容的行过滤
                if (s.contains("[ar:")
                    || s.contains("[ti:")
                    || s.contains("[by:")
                    || s.contains("[al:")
                    || s.equals("")) {
                    continue;
                }

                s = s.replace("[", "");

                //关键代码，歌词用的时候需要对时间进行排序
                String[] splitLrcData = s.split("]");

                for (int i = 0; i < splitLrcData.length - 1; i++) {
                    mLrcContent.setLrcTime(TimeStr(splitLrcData[i]));
                    mLrcContent.setLrc(splitLrcData[splitLrcData.length - 1]);
                    lrcList.add(mLrcContent);
                    mLrcContent = new LrcContent();
                }
                //关键代码
            }
            br.close();
            isr.close();
        } catch (Exception e) {
            e.printStackTrace();
            stringBuilder.append(NO_LYRIC_DATA);
            return stringBuilder.toString();
        }
        return stringBuilder.toString();
    }

    /**
     * 处理时间
     * 时间转换为毫秒millisecond
     */
    public static long TimeStr(String timeStr) {
        timeStr = timeStr.replace(".", ":");
        String[] timeData = timeStr.split(":");
        long currentTime = 0;
        // 分离出分、秒并转换为整型
        try {
            long minute = Integer.parseInt(timeData[0]);
            long second = Integer.parseInt(timeData[1]);
            long millisecond = Integer.parseInt(timeData[2]);
            currentTime = (minute * 60 + second) * 1000 + millisecond * 10;
        } catch (Exception ex) {
            ex.printStackTrace();
        }
        return currentTime;
    }

    /**
     * 获取解析完成的歌词列表
     *
     * @return 歌词列表
     */
    public static List<LrcContent> getLrcContent() {
        Collections.sort(lrcList);
        return lrcList;
    }
}
